package com.xinenhua.businessserver.personal;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.view.View;
import android.widget.AdapterView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.kennyc.view.MultiStateView;
import com.oasis.oasislib.base.BaseFragment;
import com.oasis.oasislib.utils.LogUtil;
import com.oasis.oasislib.utils.ToastUtils;
import com.oasis.oasislib.view.XListView;
import com.xinenhua.businessserver.Const;
import com.xinenhua.businessserver.R;
import com.xinenhua.businessserver.contract.ContractDetail;
import com.xinenhua.businessserver.http.BaseHttp;
import com.xinenhua.businessserver.login.pojo.User;
import com.xinenhua.businessserver.personal.customer.AllCustomerPojo;
import com.xinenhua.businessserver.personal.order.OrderAdapter;
import com.xinenhua.businessserver.personal.order.OrderListPojo;


import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.ViewInject;

import java.io.IOException;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

/**
 *
 */
@ContentView(R.layout.list)
public class SimpleCardFragment extends BaseFragment implements XListView.XListViewListener{

    String whichType;

    String isfic="";  //1  虚拟   2  代表实体

    @ViewInject(R.id.multiStateView)
    MultiStateView multiStateView ;

    @ViewInject(R.id.xlist_campaign)
    XListView xListView ;

    String mTitle;

    OrderAdapter adapter;

    ArrayList<OrderListPojo> list = new ArrayList<>() ;

    public String mbuild_id;
    public String entity_status="";


    private boolean hasMoreData = true ;
    private int pageIndex = 1 ;

    User user;


    public static SimpleCardFragment getInstance(String whichType,String isfic) {
        SimpleCardFragment sf = new SimpleCardFragment();
        sf.whichType = whichType;
        sf.isfic = isfic;
        return sf;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        LogUtil.e(TAG,"whichType---"+whichType);
        user = Const.getUser();
    }

    @Override
    protected void start() {


        multiStateView.setViewState(MultiStateView.VIEW_STATE_LOADING);
        xListView.setPullLoadEnable(true);
        xListView.setPullRefreshEnable(true);
        xListView.setHeaderProgressDrawable(ContextCompat.getDrawable(getActivity(),R.mipmap.default_ptr_rotate));
        xListView.setRefreshTime();
        xListView.setPULL_LOAD_MORE_DELTA(60);
        xListView.setSCROLL_DURATION(400);
        xListView.setOFFSET_RADIO(3.0f);
        xListView.setXListViewListener(this);

        adapter = new OrderAdapter(getActivity()) ;
        adapter.setList(list);
        xListView.setAdapter(adapter);
        xListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                Intent openWelcomeActivityIntent=new Intent();
                Bundle bundle=new Bundle();
                bundle.putString("ding",String.valueOf(list.get(position-1).getDingdanhao()));
                openWelcomeActivityIntent.putExtras(bundle);
                openWelcomeActivityIntent.setClass(getActivity(), ContractDetail.class);
                startActivity(openWelcomeActivityIntent);
            }
        });

        getData();


    }


    @Override
    public void onRefresh() {
        list.clear();
        pageIndex = 1 ;
        multiStateView.setViewState(MultiStateView.VIEW_STATE_LOADING);
        adapter.notifyDataSetChanged();
        getData();
    }

    @Override
    public void onLoadMore() {
        if (hasMoreData) {
            getData() ;
        }else {
            xListView.hideFooter();
        }
    }


    private void getData() {


        HashMap<String,String> map = new HashMap<>() ;
        map.put("list_rows",String.valueOf(Const.list_rows));
        map.put("page",String.valueOf(pageIndex));
        map.put("type",isfic); //1实体 2虚拟
        map.put("zhangdan_status",whichType);//状态：为空显示全部；2 已生成待上传缴费 3 待业务审核 4 待财务审核 5 完成
        map.put("admin_id",user.getAdmin_id()+"");

        Call call = BaseHttp.getCallWithUrlAndData(Const.Servicecontract,map);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                System.out.println("Fail");

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String rr = new String(response.body().string());
                LogUtil.e(TAG,"onResponse---"+rr);
                int result = BaseHttp.preResult(rr);
                if(result==BaseHttp.DATA_OK){
                    String s = BaseHttp.getJsonDataAsString(rr);

                    final int total = BaseHttp.getJsonDataAsInt(s,"total") ;
                    int per_page = BaseHttp.getJsonDataAsInt(s,"per_page") ;
                    final int current_page = BaseHttp.getJsonDataAsInt(s,"current_page") ;
                    int last_page = BaseHttp.getJsonDataAsInt(s,"last_page") ;


                    String ssss = BaseHttp.getJsonDataAsString(s);


                    Gson gson = new Gson();
                    Type listType = new TypeToken<List<OrderListPojo>>(){}.getType();
                    List<OrderListPojo> orderlist = gson.fromJson(ssss, listType);

                    list.addAll(orderlist);

                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {

                            if(total==0){
                                multiStateView.setViewState(MultiStateView.VIEW_STATE_EMPTY);
                            }else {
                                adapter.notifyDataSetChanged();
                                multiStateView.setViewState(MultiStateView.VIEW_STATE_CONTENT);

                                xListView.setRefreshTime();
                                xListView.stopLoadMore();
                                xListView.stopRefresh();

                                if(list.size()<total){
                                    hasMoreData = true ;
                                    pageIndex = current_page+1 ;
                                }else {
                                    hasMoreData = false ;
                                }

                                if (hasMoreData) {
                                    xListView.showFooter();
                                } else {
                                    xListView.hideFooter();
                                }
                            }

                        }
                    });


                }else {
                    ToastUtils.shortToast(getActivity(),BaseHttp.getJsonMsg(rr));

                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            adapter.notifyDataSetChanged();
                            multiStateView.setViewState(MultiStateView.VIEW_STATE_ERROR);

                            xListView.setRefreshTime();
                            xListView.stopLoadMore();
                            xListView.stopRefresh();
                        }
                    });
                }

            }
        });


    }
}
